# -*- coding: utf-8 -*-
import logging
import time
from traceback import format_exc
from selenium import webdriver
from scrapy.utils.project import get_project_settings
from selenium.webdriver.support.select import Select
from zc_core.dao.cookie_dao import CookieDao

logger = logging.getLogger('login')


class SeleniumLogin(object):
    # 登录地址
    login_url = 'https://zc.plap.mil.cn/'
    cookie_key_filter = ['_session_id']

    def __init__(self, timeout=60):
        settings = get_project_settings()
        self.max_login_retry = settings.get('MAX_LOGIN_RETRY', 1)
        self.timeout = timeout
        self.option = webdriver.FirefoxOptions()
        # self.option.add_argument('--headless')
        self.option.add_argument('--no-sandbox')
        self.accounts = settings.get('ACCOUNTS', {})

    def new_chrome(self):
        self.browser = webdriver.Firefox(firefox_options=self.option)
        self.browser.set_window_size(1400, 900)
        self.browser.set_page_load_timeout(self.timeout)

    def login(self, customer):
        try:
            self.new_chrome()
            self.browser.get(self.login_url)
            time.sleep(2)
            self.browser.refresh()
            time.sleep(3)

            accounts = self.accounts.get(customer, [])
            if not accounts or not len(accounts):
                raise Exception('客户账号未配置: %s' % customer)
            account = accounts[0]

            logger.info('login account: %s' % account)
            login_button = self.browser.find_elements_by_class_name('user-action-btn')[0]
            login_button.click()
            self.browser.switch_to.frame('layui-layer-iframe6')
            time.sleep(5)
            supplier_button = self.browser.find_element_by_id("waiselected")
            supplier_button.click()

            username = self.browser.find_element_by_id("loginid")
            username.clear()
            username.send_keys(account.get('acc'))
            time.sleep(1)

            password = self.browser.find_element_by_id("loginpwd")
            password.clear()
            password.send_keys(account.get('pwd'))
            time.sleep(1)

            # 登录
            btn = self.browser.find_element_by_class_name("lognbtn")
            btn.click()
            time.sleep(10)

            self.browser.switch_to.default_content()
            # 校验
            cookies = self.browser.get_cookies()
            logger.info('--> cookies: %s' % cookies)

            self.browser.close()
            return cookies
        except Exception as e:
            _ = e
            logger.error(format_exc())
            self.browser.close()
            return list()

    # cookie获取
    def get_cookies(self, customer):
        settings = get_project_settings()
        key = 'zc:cookie:{}'.format(settings.get('BOT_NAME'))
        cookie_dao = CookieDao()
        cookies = cookie_dao.get_cookie(key=key)
        if not cookies:
            cookies = self.__get_cookies(0, customer)
            cookie_dao.save_cookie(cookies=cookies, key=key)
        return cookies

    # 最大重试登录获取cookie
    def __get_cookies(self, retry, customer):
        # 登录获取
        arr = self.login(customer)
        if not arr:
            # 失败重试
            if retry <= self.max_login_retry:
                retry = retry + 1
                logger.info('--> 登录失败重试: %s次' % retry)
                return self.__get_cookies(retry, customer)
            else:
                logger.info('--> 放弃失败重试: %s次' % retry)
                return dict()

        # 重组
        cookies = dict()
        for cookie in arr:
            # 敏感过滤
            cookies[cookie.get('name')] = cookie.get('value')

        # 校验
        if not cookies or not self._validate_cookie(cookies):
            # 失败重试
            if retry <= self.max_login_retry:
                retry = retry + 1
                logger.info('--> 登录失败重试: %s次' % retry)
                return self.__get_cookies(retry, customer)
            else:
                logger.info('--> 放弃失败重试: %s次' % retry)
                return dict()

        logger.info('--> 登录成功: %s次' % retry)
        return cookies

    # cookie校验
    def _validate_cookie(self, cookies):
        return True


if __name__ == '__main__':
    SeleniumLogin().login("spu")
